#include "../include/head.h"
#include "../include/func.h"

#define COMMAND_TRAIN_LENGTH ((sizeof(int)) + (sizeof(CmdType)) + (sizeof(User_t)) + (command_train.len))

int main(int argc, char *argv[]){                                  
    ARGS_CHECK(argc, 2);

    // 从bin下的配置文件拿到服务器的ip和port
    char server_ip[16] = "";
    char server_port[6] = "";
    conf_get(argv[1], server_ip, server_port);

    // 与服务器建立tcp连接
    int sockfd = tcp_connect(server_ip, server_port);

    // 初始化一个用户注册表
    User_t user = {0};
    login_view(sockfd, &user);

    // 执行指令模块
    printf("\033[1;94m---------------请输入命令-----------------\033[0m\n");
    char buf[4096] = {0};
    fd_set readyset = {0};
    train_t command_train = {0};
    
    while (1) {
        FD_ZERO(&readyset);
        FD_SET(STDIN_FILENO, &readyset);
        FD_SET(sockfd, &readyset);

        int readynum = select(sockfd + 1, &readyset, NULL, NULL, NULL);
        if (FD_ISSET(STDIN_FILENO, &readyset)) {
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            buf[strlen(buf) - 1] = '\0'; 
            if (ret == 0) {
                printf("拜拜了您嘞！\n");
                break;
            }
            memset(&command_train, 0, sizeof(train_t));
            // 解析命令
            parseCommand(buf, strlen(buf), &command_train, &user);
            // 修改发送命令的类型
            send(sockfd, &command_train, COMMAND_TRAIN_LENGTH, 0);
            if (command_train.type == CMD_TYPE_PUTS) {
                putsCommand(sockfd, &command_train);
                printf("\033[1;94m---------------命令执行完毕-----------------\033[0m\n");
            }
        } else if (FD_ISSET(STDIN_FILENO, &readyset)) {
            memset(buf, 0, sizeof(buf));
            if (command_train.type == CMD_TYPE_GETS) {
                getsCommand(sockfd, &command_train);
            } else {
                int ret = recv(sockfd, &buf, sizeof(buf), MSG_WAITALL);
                if (ret == 0) {
                    break;
                }
                printf("%s\n", buf); // 接收命令执行结果
            }
            printf("\033[1;94m---------------命令执行完毕-----------------\033[0m\n");
        }
    }

    close(sockfd);
    return 0;
}

